import React from 'react'
import { connect } from 'dva'
import { Router, Route, Switch, Redirect } from 'dva/router'
import functions from './functions.json'
import dynamic from 'dva/dynamic'

String.prototype.firstUpperCase = function () {
    return this.replace(/^\S/, S => {
        return S.toUpperCase()
    })
}
const pubicMoadl = {}
function getRouterData(app) {
    const routerData = {}
    console.log(app)
    functions.forEach(item => {
        const [name] = item.name.split('/')
        if (pubicMoadl[name]) return
        const model = require(`./models/${name}.js`)
        if (model === name) {
            throw new Error(`src/models/${name}.js`)
        }
        if (!model.state) {
            model.state = {}
        }
        if (!model.namespace) {
            model.namespace = name
            pubicMoadl[name] = true
        }
        if (!model.effect) {
            model.effect = {}
        }
        if (!model.reducers) {
            model.reducers = {
                setState(state, newState) {
                    return { state, ...newState }
                }
            }
        }
        if (model.subscriptions && model.subscriptions.setup) {
            const { setup } = model.subscriptions
            model.subscriptions.setup = function (data) {
                setup({ funCode: item.code, ...data })
            }
        }
        app.model(model)
    })

    functions.forEach(item => {
        const [name] = item.name.split('/')
        routerData[item.code] = {
            component: connect(item.connect ? item.connect : state => ({
                ...state.global,
                ...state[name],
                loading: state.loading.models[name],
                effects: state.loading.effects,
                context: item
            })
            )(
                dynamic({
                    app,
                    component: () => require(/* webpackChunkName:"[request]" */`./routes/${item.name}`)
                })
            )
        }

    })

    return routerData
}

function router() {
    return function RouterConfig({ history, app }) {
        const routerData = getRouterData(app)
        const routers = []
        Object.keys(routerData).forEach(key => {
            routers.push({
                key: `/${key}`,
                path: `/${key}`,
                component: routerData[key].component,
                exact: true
            })
        })
        return (
            <Router history={history}>
                <Switch>
                    <Route exact path="/" render={() => <Redirect to="/JXT000001" />} />
                    {
                        routers.map(item => {
                            return (<Route key={item.key} path={item.path} component={item.component} />)
                        })
                    }
                </Switch>

            </Router>
        )
    }
}

export default router